//: Playground - noun: a place where people can play

import UIKit

class Person {
    // 如果属性是值类型, 则初始化为空值
    // 如果属性是对象类型, 则初始化为nil
    var name : String = ""
    var age : Int = 0
    var view : UIView? = nil
}

// 创建对象
let person = Person()
person.name = "Alex"
person.age = 23
person.view = UIView()
person


//// 类的属性定义

class Student {

    // 存储属性
    var name : String = ""
    var age : Int = 20
    var chineseScore : Double = 0
    var mathScore : Double = 0

    // 计算属性
    var average : Double {
        set {

        }
        get {
            return (chineseScore + mathScore) * 0.5
        }
    }

    // 类属性 (只能通过类名访问)
    static var examCount : Int = 0
}
let student = Student()
student.name = "Alex"
student.age = 23
student.chineseScore = 30
student.mathScore = 50
let average = student.average
print(average)
Student.examCount = 10


// 类的属性监听

class Animal {
    var width : Double = 0
    var name : String = "" {
        willSet {
            print("newValue:\(newValue)")
        }
        didSet {
            print("oldValue:\(oldValue)")
        }
    }
}

let a = Animal()
a.name = "Dog"


// 类的构造函数

class Computer : NSObject {
    var model : String = ""
    var price : Int = 0

    // 构造函数会覆盖内部的构造函数
    init(model : String, price : Int) {
        self.model = model
        self.price = price
    }

    // 属性如果很多, 使用KVC进行赋值
    // 条件: 
    // 1. 继承自NSObject
    // 2. 必须在构造函数中, 先调用super.init()
    // 3. 调用 setValuesForKeys
    // 4. 如果字典中某一个key没有对应属性, 需要调用  setValue(_ value: Any?, forUndefinedKey key: String)
    init(dict : [String : Any]) {
        super.init()
        setValuesForKeys(dict)
    }

    override func setValue(_ value: Any?, forUndefinedKey key: String) {}

}

let c = Computer(model: "MacBookPro", price: 10000)
let c1 = Computer(dict: ["model" : "Windows", "price" : 4000, "color" : "black"])



// 类的析构函数
class Book {
    var title : String = ""
    var price : Int = 0

    deinit {
        print("book-deinit")
    }
}

var b : Book? = Book()
b = nil

